﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace PwjCy.Lite.Common
{
    public sealed class XmlHelper
    {
        private static readonly Lazy<XmlHelper> lazy = new Lazy<XmlHelper>(() => new XmlHelper());
        private XmlHelper() { }
        public static XmlHelper Instance { get { return lazy.Value; } }
        public string SerailizeXml<T>(T obj)
        {
            string result = null;
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding(false)) { Formatting = Formatting.Indented };
                    xmlSerializer.Serialize(xmlTextWriter, obj);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();
                    result = new UTF8Encoding(false, true).GetString(memoryStream.ToArray());
                }
            }
            catch (Exception innerException)
            {
                throw new ApplicationException("Couldn't Serialize Object:" + obj.GetType().Name, innerException);
            }
            return result;
        }
        public T Deserizlize<T>(string xml)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            object result;
            try
            {
                using (StringReader stringReader = new StringReader(xml))
                {
                    result = xmlSerializer.Deserialize(stringReader);
                }
            }
            catch (Exception innerException)
            {
                bool flag = null == xml ? false : xml.StartsWith(Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()));
                throw new ApplicationException(string.Format("Couldn't parse XML: '{0}'; Contains BOM: {1}; Type: {2}.", xml, flag, typeof(T).FullName), innerException);
            }
            return (T)result;
        }
    }
}
